﻿using System.ComponentModel.Composition;
using Cubicle.Core.Interfaces;

namespace Cubicle.Core.Processors.Parameter
{
    [Export("Cubicle.Processors.Parameter.HandleStringParameterResolver", typeof(IProcessor<ParameterRequest>))]
    [ExportMetadata("Name", "HandleStringParameterResolver")]
    [ExportMetadata("Description", "Resolves handles from a repository.")]
    public class HandleStringParameterResolver : ConditionalProcessor<ParameterRequest>
    {

        [Import] private IRepository _repo;

        #region Overrides of Processor<ParameterRequest>

        public override bool Condition(ParameterRequest request)
        {
            return request.Source is string;
        }

        public override ParameterRequest ConditionalProcess(ParameterRequest request)
        {
            var strValue = (string)request.Source;
            var result = _repo.Get(strValue);

            // Check if the value is in the repository
            if (result == null)
                return request;

            // Check if the value is assignable to the target type
            if (!request.TargetType.IsAssignableFrom(result.GetType()))
                return request;

            // Complete request
            request.Complete(result);
            return request;
        }

        #endregion
    }
}